package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.service.BusinessService;
import jakarta.servlet.http.HttpSession;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.neusoft.elmboot.dto.UserDTO;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;

@RestController
@RequestMapping("/UserController")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private BusinessService businessService;

	@PostMapping("/getUserByIdByPass")
	public UserDTO getUserByIdByPass(@RequestBody User user, HttpSession session, HttpServletResponse response) {

		try {
			UserDTO userDTO = userService.getUserByIdByPass(user);

			if (userDTO != null) {
				session.setAttribute("userId", userDTO.getUserId());

				Business business = businessService.getBusinessByUserId(userDTO.getUserId());
				if (business != null) {
					userDTO.setBusinessId(business.getBusinessId());
				}

				// 确保返回的 userDTO 中有 userImg 属性
				if (userDTO.getUserImg() == null || userDTO.getUserImg().isEmpty()) {
					userDTO.setUserImg(""); // 保证 userImg 不为 null
				}

				// 添加 Cookie
				Cookie cookie = new Cookie("token", user.getUserId());
				cookie.setPath("/");
				response.addCookie(cookie);

				return userDTO;

			} else {
				System.out.println("UserDTO is null");
				return new ResponseEntity<UserDTO>(HttpStatus.NOT_FOUND).getBody();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	@GetMapping("/getUserById")
	public User getUserById(@RequestParam String userId) throws Exception {
		return userService.getUserById(userId);
	}

	@PostMapping("/saveUser")
	public int saveUser(@RequestBody User user, HttpServletResponse response) {
		try {
			int result = userService.saveUser(user);

			if (result > 0) {
				Cookie cookie = new Cookie("token", user.getUserId());
				cookie.setPath("/");
				response.addCookie(cookie);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

}
